package com.hg.design.behavior.memento.biancheng.ex3;

import java.util.LinkedList;
import java.util.List;

//原型管理者
public class PrototypeCaretaker {
    private List<OriginatorPrototype> opts;
    private int max;//最大数量
    private int index;//当前数量

    public PrototypeCaretaker(int max){
        this.opts = new LinkedList<>();
        if (max < 1) {
            throw new RuntimeException("创建管理者失败：最多可撤销次数错误");
        }
        this.max = max;
        this.index = 0;
    }

    public OriginatorPrototype getMemento() {
        OriginatorPrototype opt;
        if (this.opts.size() > 1) {
            opt = this.opts.get(this.index - 1);
            this.index -= 1;
            if (this.index < this.opts.size() - 1) {
                this.opts.remove(this.opts.size() - 1);
            }
        } else {
            opt = this.opts.get(0);
            this.index = 1;
        }

        System.out.print("撤销状态后剩余可撤回状态：");
        this.opts.forEach(s -> System.out.print(s.getState() + ", "));
        System.out.println();

        return opt;
    }

    public void setMemento(OriginatorPrototype opt) {
        if (this.index >= this.max)
            this.opts.remove(0);
        this.opts.add(opt);
        this.index = this.opts.size();

        System.out.print("保存状态后剩余可撤回状态：");
        this.opts.forEach(s -> System.out.print(s.getState() + ", "));
        System.out.println();
    }
}
